<script>
import { watch, reactive, computed } from "vue";
import Taro from "@tarojs/taro";
import { getDicMap, getColdCompany } from "@/utils/storage";
import { date2Str } from "@/utils/date";
import { useTzRouter } from "@/vhooks/useTzRouter";
import { useCarInfo } from "./useCarInfo";
import { usetrayInfo } from "./useTrayInfo";
import { useboxingInfo } from "./useBoxingInfo";
import { saveConsist } from "../api";
import { useMountData } from "./useMountData";
export default {
  name: "BundleHome",
  components: {},
  setup() {
    const dicMap = getDicMap();
    const coldCompany = getColdCompany();
    const {
      route,
      EventChannel,
      navigateTo,
      redirectTo,
      navigateBack,
    } = useTzRouter();

    const state = reactive({
      typeIndex: 0,
      deparrdt: "点击选择货运日期",
      carInfo: null, // Object or null
      portsList: dicMap.customsCodeList,
      trayInfo: null, // 托架信息 Object or null
      boxingInfo: null, // 集装箱 Array or null
      truckOrderType: "", // 重车、空车、无柜空车类型
      customsCode: "", // 口岸代码
      detailToEdit: route.query.detailToEdit || 0,
      disabledBtn: false,
    });

    watch(
      () => state.showLoading,
      (val) => {
        if (val) {
          Taro.showLoading({
            title: "加载中",
            icon: "none",
          });
          state.disabledBtn = true;
        } else {
          Taro.hideLoading();
          state.disabledBtn = false;
        }
      }
    );

    // =============== 路由参数处理 ===============
    const truckOrderType = route.query.type || ""; // 车辆类型
    state.truckOrderType = truckOrderType;

    const truckPayloadType = {
      isNoBoxEmptyCar: truckOrderType === "1", // 无柜空车捆绑
      isHasBoxEmptyCar: truckOrderType === "2", // 有柜空车捆绑
      isHeavyCar: truckOrderType === "3", // 重车捆绑
    };
    state.truckPayloadType = truckPayloadType;

    const handleType = route.query.opt === "1" ? "edit" : "add";

    // 修改标题
    let navBarTitle = "";
    if (truckPayloadType.isNoBoxEmptyCar) {
      navBarTitle = "空载确报";
    } else if (truckPayloadType.isHasBoxEmptyCar) {
      navBarTitle = "搭载空箱确报";
    } else if (truckPayloadType.isHeavyCar) {
      navBarTitle = "重车确报";
    }

    if (handleType === "edit") {
      navBarTitle += "编辑";
    } else {
      navBarTitle += "添加";
    }
    Taro.setNavigationBarTitle({ title: navBarTitle });

    // 从详情过来编辑数据，接口获取数据回显
    if (route.query.consistId) {
      useMountData({ state, consistId: route.query.consistId });
    }

    // =============== EventChannel 处理 ===============
    EventChannel.on(route.path, (event) => {
      // 车辆选择回传数据
      if (event?.type === "truckHomeBack") {
        state.carInfo = event.data;
        event.data.trailer && (state.trayInfo = event.data.trailer);
        state.boxingInfo = event.data.boxing;
        if (state.carInfo.truckLicenseName.indexOf("澳") > -1) {
          state.portsList = [
            { para_value: "", para_name: "--请选择--" },
            { para_value: "5795", para_name: "5795横琴海关" },
            { para_value: "5710", para_name: "5710闸口海关" },
            { para_value: "5791", para_name: "5791拱跨工区" },
            { para_value: "5788", para_name: "5788大桥海关" },
          ];
        } else {
          state.portsList = dicMap.customsCodeList;
        }
        state.truckType = {
          isContainer: event.data.truckType === "1", // 货柜车
          isTon: event.data.truckType === "0", // 吨车
        };
        const { trailer, boxing } = event.data;
        if (!dicMap.userType.isPersonal) {
          if (trailer) {
            if (
              boxing &&
              !Array.isArray(boxing) &&
              typeof boxing !== "object"
            ) {
              state.trayInfo = JSON.parse(trailer);
            }
          }
          if (boxing) {
            if (!Array.isArray(boxing) && typeof boxing !== "object") {
              state.boxingInfo = JSON.parse(boxing);
            }
          }
          if (state.boxingInfo && Array.isArray(state.boxingInfo)) {
            state.boxingInfo.forEach((item) => {
              if (!item.boxingSourceCode) {
                item.boxingSourceCode = "5";
              }
              item.fullOrEmptyCode = "5";
            });
          }
        }
      } else if (event?.type === "trayAddBack") {
        // 托架添加返回
        if (state.trayInfo === null) {
          state.trayInfo = event.data;
        } else {
          state.trayInfo = { ...state.trayInfo, ...event.data };
        }
      } else if (event?.type === "boxInfoAddBack") {
        // 集装箱添加返回
        if (state.boxingInfo && state.boxingInfo.length) {
          if (event.data.boxingIndex) {
            // 编辑数据返回
            Object.assign(state.boxingInfo[event.data.boxingIndex], event.data);
          } else {
            state.boxingInfo.push(event.data);
          }
        } else {
          state.boxingInfo = [event.data];
        }
        state.carInfo.boxing = state.boxingInfo;
      } else if (event?.type === "deleteTray") {
        // 删除托架数据
        state.trayInfo = null;
      } else if (event?.type === "deleteBoxingInfo") {
        // 删除集装箱数据
        if (event.data.boxingCode) {
          const targetIndex = state.boxingInfo.findIndex(
            (item) => item.boxingCode === event.data.boxingCode
          );
          state.boxingInfo.splice(targetIndex, 1);
        }
      }
    });

    // =============== 提交校验-start ===============

    // 弹出确认 modal
    const confirmMan = (ruleFn) => {
      return new Promise((resolve, reject) => {
        try {
          ruleFn();
          resolve();
        } catch (err) {
          Taro.showModal({
            content: err.message,
            confirmText: "是",
            cancelText: "否",
          }).then((res) => {
            if (!res.confirm) {
              reject("cancel");
            } else {
              resolve();
            }
          });
        }
      });
    };

    const checkFormData = (data) => {
      const { truckList, docCode, customsCode } = data;
      try {
        if (!truckList || !truckList.length) {
          throw new Error("请输入车辆信息");
        }
        if (!docCode || !docCode.trim()) {
          throw new Error("请输入六联单号");
        }
        if (!customsCode || !customsCode.trim()) {
          throw new Error("请选择进出境口岸");
        }
        return true;
      } catch (err) {
        Taro.showToast({
          title: err.message,
          icon: "none",
          duration: 2000,
        });
        return false;
      }
    };

    // 校验司乘人员相关信息
    const checkPassengerPersonnel = (data) => {
      return confirmMan(() => {
        const truck = data.truckList[0];
        if (data.docCode[0] === "1") {
          // 1 开头为进口
          if (!truck.numStaffMember || truck.numStaffMember === "0") {
            throw new Error("司乘人员数为空，是否继续？");
          }
          if (!truck.rountingCountryCode) {
            throw new Error("途径国家为空，是否继续？");
          }
        }
      });
    };

    // 校验托架
    const checkTrayInfo = (data) => {
      /**
       * （根据旧项目页面交互整理，后续根据现有需求调整）
       * 托架校验规则：
       *   无柜空车：货柜车 && 没有填写托架信息 -> 弹出确认弹框 -> 确认则提交
       *   有柜空车： 必须填写托架信息 弹出错误提示
       *   重车：货柜车 && 没有填写托架信息 -> 必须填写 弹出错误提示
       */
      const truckType = data.truckList[0].truckType;

      if (
        truckPayloadType.isNoBoxEmptyCar &&
        truckType === "1" &&
        !state.trayInfo
      ) {
        // 无柜空车
        return confirmMan(() => {
          throw new Error("托架信息未填写，是否继续？");
        });
      } else if (truckPayloadType.isHasBoxEmptyCar && !state.trayInfo) {
        // 有柜空车
        Taro.showToast({
          title: "请输入托架信息",
          icon: "none",
          duration: 2000,
        });
        return Promise.reject();
      } else if (
        truckPayloadType.isHeavyCar &&
        truckType === "1" &&
        !state.trayInfo
      ) {
        // 重车
        Taro.showToast({
          title: "请输入托架信息",
          icon: "none",
          duration: 2000,
        });
        return Promise.reject();
      }
      return Promise.resolve();
    };

    // 校验集装箱信息
    const checkBoxing = (data) => {
      /**
       * （根据旧项目页面交互整理，后续根据现有需求调整）
       * 集装箱校验规则：
       *   有柜空车： 必须填写集装箱信息 弹出错误提示
       *   重车：货柜车 && 没有填写集装箱信息 -> 弹出确认弹框 -> 确认则提交
       *         吨车 && 没有填写集装箱信息 -> 直接提交
       */
      const truckType = data.truckList[0].truckType;
      if (
        truckPayloadType.isHasBoxEmptyCar &&
        (!state.boxingInfo || !state.boxingInfo.length)
      ) {
        // 有柜空车
        Taro.showToast({
          title: "请输入集装箱信息",
          icon: "none",
          duration: 2000,
        });
        return Promise.reject();
      } else if (
        truckPayloadType.isHeavyCar &&
        (!state.boxingInfo || !state.boxingInfo.length)
      ) {
        if (truckType === "1") {
          return confirmMan(() => {
            throw new Error("未填写集装箱信息，是否继续？");
          });
        } else if (truckType === "0") {
          return Promise.resolve();
        }
      }
      return Promise.resolve();
    };
    // =============== 提交校验-end ===============

    const saveClick = async () => {
      if (state.showLoading) return;
      const params = state.cacheEditFormData
        ? { ...state.cacheEditFormData }
        : {};

      // 只有重车有 其他 输入框
      if (truckPayloadType.isHeavyCar) {
        params.others = state.others || "";
      }

      if (truckPayloadType.isHasBoxEmptyCar) {
        // 装货地代码默认为口岸代码
        params.unloadingAddressCode = state.customsCode;
        // 货物通关代码默认为RD11
        params.goodsCustomsCode = "RD11";
      }

      Object.assign(params, {
        docCode: state.docCode,
        customsCode: state.customsCode,
        deparrdt: date2Str(new Date()),
        type: state.truckOrderType,
        orderType: dicMap.userType.isPersonal ? 1 : 2,
      });
      const truckList = [];
      const { carInfo, trayInfo } = state;
      // 处理车辆信息
      if (carInfo && Object.keys(carInfo).length) {
        //香港车辆信息字段数据转换
        if (carInfo.hkTruckLicenseName) {
          carInfo.truckLicenseNameHongKong = carInfo.hkTruckLicenseName;
        }

        // 托架信息
        const trayInfoObj = {
          trailerCode: null,
          trailerTypeCode: null,
          trailerWeight: null,
          isEnable: null,
          generatorWeight: null,
        };
        Object.assign(carInfo, trayInfoObj, trayInfo);
        // 集装箱信息
        const boxingInfo = state.boxingInfo
          ? JSON.parse(JSON.stringify(state.boxingInfo))
          : state.boxingInfo;
        if (boxingInfo?.length) {
          boxingInfo.forEach((item) => {
            if (item.boxingSealed) {
              item.boxingSealed = truckPayloadType.isHeavyCar
                ? item.boxingSealedType +
                  "/" +
                  item.boxingSealed +
                  "@" +
                  item.boxingSealedName
                : null;
            }
          });
          carInfo.truckBoxings = boxingInfo;
          carInfo.boxing = boxingInfo;
        }
        truckList.push(carInfo);
      }

      // 原有逻辑：如果为空载确报，车辆带出的数据里面有集装箱信息，就删掉集装箱信息
      if (truckPayloadType.isNoBoxEmptyCar && carInfo && carInfo.truckBoxings) {
        carInfo.truckBoxings = null;
      }
      params.truckList = truckList;
      if (!checkFormData(params)) return;

      try {
        // 校验司乘人员相关信息
        await checkPassengerPersonnel(params);
        // 托架校验
        await checkTrayInfo(params);

        // 校验集装箱信息
        await checkBoxing(params);
        // 通过车牌带出的集装箱信息可能没有 类型尺寸和来源，需要校验
        const truckBoxings = params.truckList[0].truckBoxings;
        try {
          if (truckBoxings && truckBoxings.length) {
            truckBoxings.forEach((item) => {
              if (!item.boxingSizeType || !item.boxingSizeType.trim()) {
                throw new Error("请选择集装箱类型尺寸");
              }
              if (!item.boxingSourceCode) {
                throw new Error("请选择集装箱来源");
              }
            });
          }
        } catch (err) {
          Taro.showToast({
            title: err.message,
            icon: "none",
            duration: 2000,
          });
          return false;
        }
        params.truckList?.forEach((item) => {
          item.isEnable = item.isEnable ? "01" : "00";
          // 存在 consistId, 车辆数据带上 consistId
          if (route.query.consistId) {
            // item.consistId = route.query.consistId;
            // 编辑的时候去掉 truckId
            item.truckId && delete item.truckId;
            // 编辑的时候去掉 trailerId
            item.trailerId && delete item.trailerId;
          }
        });
        // return;
        state.showLoading = true;
        saveConsist(params)
          .then((res) => {
            state.showLoading = false;
            Taro.showToast({
              icon: "success",
              title: "操作成功",
              success: function () {
                if (route.query.consistId) {
                  // 从详情页过来编辑
                  navigateBack({
                    delta: 1,
                    event: {
                      type: "editBackRefresh", // 编辑页回退
                    },
                  });
                } else {
                  // 新增数据跳转详情
                  redirectTo({
                    path: "/pages/subCN/confirm/details/index",
                    query: { consistId: res.data.consistId, isNewOrder: 1 },
                  });
                }
              },
            });
          })
          .catch((err) => {
            state.showLoading = false;
            Taro.showToast({
              title: err.data.msg || "操作失败",
              icon: "none",
              duration: 2000,
            });
          });
      } catch (err) {
        console.log("保存失败", err);
      }
    };

    const carInfoHook = useCarInfo({ state, navigateTo, dicMap });
    // 托架
    const trayInfoHook = usetrayInfo({
      state,
      navigateTo,
      dicMap,
      coldCompany,
    });
    // 集装箱
    const boxingInfoHook = useboxingInfo({
      state,
      navigateTo,
      dicMap,
    });

    const handleScan = () => {
      Taro.scanCode()
        .then((res) => {
          state.docCode = res.result;
        })
        .catch((err) => {
          console.log(err);
        });
    };

    // 展示“其他”输入框
    const showOthersInput = computed(() => {
      return state.truckPayloadType.isHeavyCar && !dicMap.userType.isPersonal;
    });

    return () => {
      return (
        <tz-view class="truck-home">
          {carInfoHook()}

          <tz-view class="form-content boder-t1 border-b1">
            <tz-cell title="六联单号" border>
              <tz-input
                v-model={state.docCode}
                type="number"
                placeholder="请输入六联单号"
                clearable
                maxlength="13"
              />
              <tz-icon name="scan" onClick={handleScan}></tz-icon>
            </tz-cell>
            <tz-cell title="口岸代码" border={showOthersInput.value}>
              <tz-picker
                mode="selector"
                range={state.portsList}
                rangeKey="para_name"
                valueKey="para_value"
                v-model={state.customsCode}
              ></tz-picker>
            </tz-cell>
            {showOthersInput.value && (
              <tz-cell title="其他">
                <tz-input
                  v-model={state.others}
                  type="text"
                  placeholder=""
                  clearable
                  maxlength="15"
                />
              </tz-cell>
            )}
          </tz-view>

          {trayInfoHook()}
          {boxingInfoHook()}

          <tz-view class="btn-content">
            <tz-button
              disabled={state.disabledBtn}
              type="primary"
              onClick={saveClick}
            >
              保存
            </tz-button>
          </tz-view>
        </tz-view>
      );
    };
  },
};
</script>

<style lang="scss">
.truck-home {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  .title-content {
    min-height: 60px;
    padding: 10px 15px;
    width: 100%;
    background: $white;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    @extend %bt1;
    @extend %bb1;
  }

  .form-content {
    width: 100%;
    background: $white;
    padding: 0 15px;
  }
  .car-info {
    width: 100%;
    display: flex;
    align-items: center;
    font-size: 13px;
    padding-bottom: 5px;
    .car-info-content {
      flex: 1;
      text {
        color: #999;
        width: 100px;
        text-align: right;
        padding-right: 10px;
        display: inline-block;
      }
      .children-flex {
        display: flex;
        > .tz-view {
          width: 50%;
        }
      }
    }
  }
  .btn-content {
    display: flex;
    justify-content: space-around;
    margin: 20px 0;
    width: 90%;
    .tz-button {
      flex: 1;
    }
  }

  // 托架
  .margin-top20 {
    margin-top: 20px;
  }
  .cell-info {
    width: 100%;
    display: flex;
    flex-direction: column;
    font-size: 12px;
    text {
      color: #999;
      width: 100px;
      text-align: right;
      padding-right: 10px;
      display: inline-block;
    }
    .tray-data {
      display: flex;
      flex-direction: column;
      width: 80%;
    }
    .del-box {
      font-size: 12px;
      color: $danger-color;
      margin-right: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
    .info-row {
      display: flex;
      width: 100%;
      justify-content: space-between;
      padding: 10px 0;
      border-bottom: 1px dotted $border-color;
      &:last-child {
        border-bottom: 0;
      }
    }
  }
}
</style>
